package com.jk.smartelderlycare.controller;



import com.jk.smartelderlycare.entity.Item;
import com.jk.smartelderlycare.pojo.PagedResponse;
import com.jk.smartelderlycare.pojo.ResponseResult;
import com.jk.smartelderlycare.utils.PaginationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.RequestEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hhk
 * @version 1.0
 * @ClassName SearchController
 * @program: smart-elderly-care
 * @description: TODO 商品搜索
 * @date 2024/11/17 20:26
 */
@Api(tags = "前台搜索模块")
@Slf4j
@RestController
@RequestMapping(value = "search")
public class SearchController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * @description: 前台商品搜索分页查询
     * @param: [keyword, pageNum, pageSize]
     * @return: com.jk.smartelderlycare.pojo.ResponseResult<com.jk.smartelderlycare.pojo.PagedResponse<com.jk.smartelderlycare.entity.Item>>
     * @author hhk
     * @date: 2024/11/17 20:30
     */
    @ApiOperation(value = "前台商品搜索分页查询",httpMethod = "GET",notes = "前台商品搜索分页查询")
    @GetMapping(value = "findItemPaginationList")
    public ResponseResult<PagedResponse<Item>> findItemPaginationList(String hashKey, String key, String keyword, Integer pageNum, Integer pageSize){
        // 获取hash的大小
        Long size = redisTemplate.opsForHash().size(hashKey);
        if (size != null && size >= 10) {
            // 如果超过10条，删除最老的数据（这里简单地删除了第一条，实际上需要确定哪条是最老的）
            String oldKey = (String) redisTemplate.opsForHash().entries(hashKey).keySet().iterator().next();
            redisTemplate.opsForHash().delete(hashKey, oldKey);
        }
        // 在插入新数据
        redisTemplate.opsForHash().put(hashKey, key, keyword);

        List<Object> list = redisTemplate.opsForHash().values(hashKey);
        list.forEach(i -> {
            System.out.println(i);
        });

        //1.创建一个空的集合
        List<Item> itemList = new ArrayList<>();
        //2.设置分页
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        //3.设置查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.should(QueryBuilders.matchQuery("title",keyword));
        boolQuery.should(QueryBuilders.matchQuery("brand",keyword));
        boolQuery.should(QueryBuilders.matchQuery("brand", keyword));
        boolQuery.should(QueryBuilders.matchQuery("seller", keyword));
        //4.设置高亮操作
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");//前缀
        highlightBuilder.postTags("</font>"); //后缀
        highlightBuilder.field("title");//标题
        highlightBuilder.field("category");//类型
        highlightBuilder.field("brand"); //品牌
        highlightBuilder.field("seller"); //卖家
        //5.构建查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQuery) //查询条件
                .withHighlightBuilder(highlightBuilder) //高亮
                .withPageable(pageRequest) //分页
                .build(); //构建查询
        //6.执行查询
        SearchHits<Item> searchHits = elasticsearchRestTemplate.search(searchQuery, Item.class);
        searchHits.forEach(searchHit -> {
            Item item = searchHit.getContent();
            //高亮设置
            item.setTitle(searchHit.getHighlightField("title").size() == 0 ? searchHit.getContent().getTitle() : searchHit.getHighlightField("title").get(0));
            item.setCategory(searchHit.getHighlightField("category").size() == 0 ? searchHit.getContent().getCategory() : searchHit.getHighlightField("category").get(0));
            item.setBrand(searchHit.getHighlightField("brand").size() == 0 ? searchHit.getContent().getBrand() : searchHit.getHighlightField("brand").get(0));
            item.setSeller(searchHit.getHighlightField("seller").size() == 0 ? searchHit.getContent().getSeller() : searchHit.getHighlightField("seller").get(0));
            itemList.add(item);
        });
        return new ResponseResult<>(200,"查询成功", PaginationUtil.getPagedResponse(itemList,pageNum,pageSize,searchHits.getTotalHits()));

    }
}
